package NoP2P;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServidorNoP2P implements Runnable {
	private Socket connection;
	  private static String nomeServidor;
	  private int ID;
	  private static int port = 19886;
	
	@Override
	public void run() {
		FileInputStream fileIn = null;
		ObjectOutputStream socketOut = null;
		 try {
			 BufferedInputStream is = new BufferedInputStream(connection.getInputStream());
		      InputStreamReader isr = new InputStreamReader(is);
		      int character;
		      StringBuffer process = new StringBuffer();
		      while((character = isr.read()) != '/') {
		        process.append((char)character);
		      }
		      String nomeArquivo = process.toString();
		      System.out.println("nome Arquivo: "+nomeArquivo);
			 
			// Criando canal de transferencia
	            socketOut = new ObjectOutputStream(connection.getOutputStream());
	         // Criando arquivo que sera transferido pelo servidor
	            File file = new File(nomeArquivo);
	            fileIn = new FileInputStream(file);
	         // Criando tamanho de leitura
	            byte[] cbuffer = new byte[4096];
	            while(true){
	            	int len = fileIn.read(cbuffer);
	            	if(len == -1) break;
	            	socketOut.write(cbuffer, 0, len);
	            }      
	      
		 	}
		    catch (Exception e) {
		      System.out.println(e);
		    }
		    finally {
		    	if (socketOut != null) {
	                try {
	                    socketOut.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
		    	if (fileIn != null) {
	                try {
	                    fileIn.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
		      try {
		        connection.close();
		     }
		      catch (IOException e){}
		    }
	}

	public static void main(String[] args) {
		 int count = 0;
		 nomeServidor = args[0];
		    try{
		      ServerSocket socket1 = new ServerSocket(port);
		      while (true) {
		        Socket connection = socket1.accept();
		        Runnable runnable = new ServidorNoP2P(connection, ++count);
		        Thread thread = new Thread(runnable);
		        thread.start();
		      }
		    }
		    catch (Exception e) {}
		  }
	public ServidorNoP2P(Socket s, int i) {
		  this.connection = s;
		  this.ID = i;
	}

	

}
